import React, {useContext, useEffect, useState} from "react";
import {CheckBox, Text} from "react-native-elements";
import {Alert, Dimensions, StyleSheet, TextInput, TouchableHighlight, TouchableOpacity, View} from "react-native";
import LocaleContext from "../libs/locale";
import {Input} from "react-native-elements/dist/input/Input";
import {fontSize_14, fontSize_15, fontSize_20} from "./theme";
import {
    addWallet,
    getChainBaseByChainID,
    getChainInfo, getWalletInfo,
    updateNowWallet,
    useWalletType,
    walletInfoType
} from "./smartxL2Libs/L2_Data";
import {getWalletByMnemonic, getWalletByPrivateKey} from "./smartxL2Libs/smartxL2Web3";
import SimpleToast from "react-native-simple-toast";

const {width,height,scale} = Dimensions.get("window");

const L2_ImportByKeyOrMnemonic = ({navigation,route}:any) => {
    const [importWay,setImportWay] = useState(route?.params?.importWay)
    const [providerUrl,setProviderUrl] = useState(route?.params?.providerUrl)
    const [chainID,setChainID] = useState(route?.params?.chainID)
    const [key,setKey] = useState("")
    const [walletName,setWalletName] = useState("")
    const [password,setPassword] = useState("")
    const [passwordCheck,setPasswordCheck] = useState("")
    const [tip,setTip] = useState("")
    const [read, setRead] = useState(false);

    useEffect(()=>{
        let title = "";
        if(importWay==="privateKey")
        {
            title = "私钥导入"
        }
        else if(importWay==="mnemonic")
        {
            title = "助记词导入"
        }
        navigation.setOptions({
            title:title
        })
        console.log(importWay)
        initNewWalletName(chainID)
    },[])
    const initNewWalletName = async (chainID:string) => {
        let net = await getChainBaseByChainID(chainID)
        if(!net)
        {
            return "";
        }
        let walletListNet = await getChainInfo(chainID);
        let name = net.coinName+"-"+(walletListNet.walletList.length+1).toString();
        setWalletName(name)
    }
    const importWallet = async () => {
        if(!read)
        {
            SimpleToast.show("您尚未阅读并同意服务及隐私条款");
            return ;
        }
        if(password==="")
        {
            SimpleToast.show("请输入密码");
            return ;
        }
        if(passwordCheck !== password)
        {
            SimpleToast.show("密码不一致");
            return ;
        }
        if(importWay === "privateKey")
        {
            try {
                let walletByKey = getWalletByPrivateKey(key);
                let walletInfo: walletInfoType = {
                    address: walletByKey.address,
                    privateKey: walletByKey.privateKey,
                    tip: tip,
                    walletName,
                    password,
                    chainID,
                    mnemonic:"",
                    balance:"0",
                };
                console.log(walletInfo)
                let addWalletRes = await addWallet(walletInfo)
                if(addWalletRes.success)
                {
                    let nowWallet:useWalletType = {chainID,providerUrl:providerUrl,address:walletByKey.address};
                    if(await updateNowWallet(nowWallet))
                    {
                        navigation.navigate("L2_Tabs");
                        return ;
                    }
                    console.log('Error:importWallet Error')
                    return ;
                }
                SimpleToast.show(addWalletRes.falseReason);
                // if(addWalletRes.falseReason === "地址已添加")
                // {
                //     return;
                //     // let nowWallet:useWalletType = {chainID,providerUrl:providerUrl,address:walletByKey.address};
                //     // if(await updateNowWallet(nowWallet))
                //     // {
                //     //     navigation.navigate("L2_Tabs");
                //     //     return ;
                //     // }
                // }
                console.log(walletInfo)
                console.log('Error:importWallet Error')
            }
            catch (e) {
                SimpleToast.show("请输入正确的私钥");
            }
            return;
        }
        else if(importWay === "mnemonic")
        {
            let wallet = getWalletByMnemonic(key);
            let walletInfoTemp = await getWalletInfo(chainID, wallet.address)
            if (walletInfoTemp) {
                SimpleToast.show("地址已经存在")
                // navigation.navigate("L2_Tabs")
                return;
            }
            let walletInfoNow: walletInfoType = {
                address: wallet.address,
                privateKey: wallet.privateKey,
                tip: tip,
                walletName: walletName,
                password: password,
                chainID,
                mnemonic: key,
                balance: "0",
            };
            let addWalletRes = await addWallet(walletInfoNow)
            if (addWalletRes.success) {
                let nowWallet: useWalletType = {chainID, providerUrl: providerUrl, address: wallet.address};
                if (await updateNowWallet(nowWallet)) {
                    navigation.navigate("L2_Tabs");
                    return;
                }
                console.log('Error:updateNowWallet Error')
                return;
            }
            SimpleToast.show(addWalletRes.falseReason);

        }

    }

    return (
        <View style={styles.container}>
            <TextInput
                placeholder={importWay==="privateKey"?"输入铭文私钥或者扫描二维码，请注意大小写":"助记词，用空格分隔"}
                style={styles.keyInputContainer}
                multiline={true}
                numberOfLines={4}
                onChangeText={value => setKey(value.trim())}
            />
            <Text style={{fontSize:fontSize_15,alignSelf:"flex-start",paddingTop:10}}>
                钱包名称
            </Text>
            <TextInput
                placeholder={walletName}
                onChangeText={value => setWalletName(value.trim())}
                style={{
                    width:"100%",fontSize:fontSize_15,padding:0,
                    paddingTop:10,borderBottomWidth:5/scale,
                    borderBottomColor:"#f0f2f3", paddingBottom:10}}
            />
            <Text style={{fontSize:fontSize_15,alignSelf:"flex-start",paddingTop:10}}>
                钱包密码
            </Text>
            <TextInput
                placeholder={"请输入密码"}
                onChangeText={value => setPassword(value.trim())}
                secureTextEntry={true}
                style={{
                    width:"100%",fontSize:fontSize_15,padding:0,
                    paddingTop:10,borderBottomWidth:5/scale,
                    borderBottomColor:"#f0f2f3", paddingBottom:10}}
            />
            <TextInput
                placeholder={"重复密码"}
                onChangeText={value => setPasswordCheck(value.trim())}
                secureTextEntry={true}
                style={{
                    width:"100%",fontSize:fontSize_15,padding:0,
                    paddingTop:10,borderBottomWidth:5/scale,
                    borderBottomColor:"#f0f2f3", paddingBottom:10}}
            />
            <Text style={{fontSize:fontSize_15,alignSelf:"flex-start",paddingTop:10}}>
                提示信息
            </Text>
            <TextInput
                placeholder={"密码提示信息（可不填）"}
                onChangeText={value => setTip(value.trim())}
                style={{
                    width:"100%",fontSize:fontSize_15,padding:0,
                    paddingTop:10,borderBottomWidth:5/scale,
                    borderBottomColor:"#f0f2f3", paddingBottom:10}}
            />
            <View
                style={{
                    flexDirection: 'row',
                    alignItems: 'center',
                    justifyContent:"flex-start",
                    width:'100%',
                    height:50
                }}
            >
                <CheckBox
                    // checkedIcon='dot-circle-o'
                    // uncheckedIcon='circle-o'
                    size={18}
                    checked={read}
                    onPress={() => setRead(!read)}
                    containerStyle={{ margin: 0, padding: 0,marginLeft:0 }}
                    checkedColor='#2980fe'
                />
                <Text style={{fontSize:fontSize_15}}>我已阅读并同意</Text>
                <Text
                    onPress={() => {}}
                    style={{ paddingLeft: 4, color: '#2a81fe',fontSize:fontSize_15 }}
                >《服务及隐私条款》</Text>
            </View>
            <TouchableHighlight underlayColor={"transparent"} onPress={()=>{
                importWallet();
            }}>
                <View style={styles.importBTN}>
                    <Text style={{fontSize:fontSize_15,color:"white"}}>导入钱包</Text>
                </View>
            </TouchableHighlight>

        </View>
    )
}
const styles = StyleSheet.create({
    container: {
        flex: 1,
        width: width,
        alignItems: "center",
        flexDirection: "column",
        paddingLeft: 10,
        paddingRight: 10,
        backgroundColor: "white"
    },
    keyInputContainer:{
        width:"100%",
        height:80,
        fontSize:fontSize_15,
        lineHeight:50,
        borderWidth:1/scale,
        borderColor: '#BFBFBFFF',
        borderRadius: 6,
        backgroundColor: '#F8FAFCFF',
        textAlignVertical:"top",
        textAlign:"left",
        padding:15,
        // paddingTop:0,
        // paddingBottom:0,
        flexWrap:"wrap",
    },
    importBTN:{
        marginTop:20,
        marginBottom:20,
        width:width-20,
        borderRadius:5,
        height:40,
        backgroundColor:"#2980fe",
        alignItems:"center",
        justifyContent:"center"
    }
})
export default L2_ImportByKeyOrMnemonic;


